
import { reqShopCartList, reqDeleteCartList, reqUpdateCheckedByid} from '@/api'
// 开启命名空间
const namespaced = true

const state = {
  cartList: []
}

const actions = {
  // 获取购物车列表
  async getShopCartList({commit}) {
    let result = await reqShopCartList()
    if (result.code === 200) {
      commit('GETSHOPCARTLIST', result.data)
    }
  },
  // 删除购物车
  async deleteCartList({commit}, skuId){
    let result =  await reqDeleteCartList(skuId)
    if (result.code === 200){
      return 'ok'
    } else {
      return new Promise.reject(new Error('删除失败'))
    }
    
  },
  // 修改状态
  async updateCheckedByid({cimmit}, {skuId, isChecked}){
   let result =  await reqUpdateCheckedByid(skuId, isChecked)
   if (result.code === 200) {
     return 'ok'
   }else {
     return Promise.reject(new Error('出错了'))
   }
  },
  // 修改全选 全不选
  trueAndFalseChecked({dispatch, getters}, isChecked){
    let promiseAll = []
    // 为 1 就是true
    if (isChecked) {
      // getters.cartList[0].cartInfoList 就是购物车数据
      getters.cartList[0].cartInfoList.forEach(item => {
        let promise = dispatch('updateCheckedByid', {skuId: item.skuId, isChecked})
        promiseAll.push(promise)
      })
    }else {
      getters.cartList[0].cartInfoList.forEach(item => {
        promiseAll.push(dispatch('updateCheckedByid', {skuId: item.skuId, isChecked}))
      })
    }
    return Promise.all(promiseAll)
  },
  // 删除已选
  deleteAllCheched({dispatch, getters}){
    let promiseAll = []
    getters.cartList[0].cartInfoList.filter(item => item.isChecked ===1 ).forEach(item => {
      let promise = dispatch('deleteCartList', item.skuId)
      promiseAll.push(promise)
    })
    return Promise.all(promiseAll)
  }

}

const mutations = {
  GETSHOPCARTLIST(state,cartList){
    state.cartList = cartList
  }
}

const getters = {
  // 购物车全部商品
  cartList(state){
    return state.cartList || []
  },
}

export default {
  namespaced,
  state,
  actions,
  mutations,
  getters
}